package com.itheima.mapper.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class FilterDemo implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String[] a = {"login.html","/HTML/","/css/","js/","register.html","/login"};

        String s = request.getRequestURL().toString();

        for (String str : a) {
            if(s.contains(str)){

                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }


        HttpSession session = request.getSession();

        Object user = session.getAttribute("user");
        System.out.println(user);

        if(user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            response.setContentType("text/html;charset=utf-8");
           response.getWriter().write("<script>alert('请先登录');location.href='login.html'</script>");
        }



    }

    @Override
    public void destroy() {

    }
}